package com.group.common.utils;

import com.group.neps.entity.Province;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 加载省份数据，配合CityLoader类进行加载
 *
 * @author 刘海翔
 * @version 1.0
 * @see CityLoader
 */
public class ProvinceLoader {
    /**
     * 加载省份数据
     *
     * @param filePath 文件路径
     * @return 省份数据
     * @throws IOException 读取文件时发生IO异常
     */
    public static HashMap<String, Province> loadProvinces(String filePath) throws IOException {
        StringBuilder jsonContent = new StringBuilder();
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line;
        while ((line = reader.readLine()) != null) {
            jsonContent.append(line);
        }
        reader.close();

        String jsonStr = jsonContent.toString();
        Pattern pattern = Pattern.compile("\\{([^\\}]+)}");
        Matcher matcher = pattern.matcher(jsonStr);

        HashMap<String, Province> provinceMap = new HashMap<>();

        while (matcher.find()) {
            String objStr = matcher.group(1);
            String code = extractValue(objStr, "code");
            String name = extractValue(objStr, "name");

            if (code != null && name != null) {
                provinceMap.put(code, new Province(code, name));
            }
        }

        return provinceMap;
    }
    /**
     * 加载省份数据，返回以省份名为键，省份编码为值的Map
     *
     * @param filePath 文件路径
     * @return 省份数据，键为省份名，值为省份编码
     * @throws IOException 读取文件时发生IO异常
     */
    public static HashMap<String, String> loadProvincesReverse(String filePath) throws IOException {
        StringBuilder jsonContent = new StringBuilder();
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line;
        while ((line = reader.readLine()) != null) {
            jsonContent.append(line);
        }
        reader.close();

        String jsonStr = jsonContent.toString();
        Pattern pattern = Pattern.compile("\\{([^\\}]+)}");
        Matcher matcher = pattern.matcher(jsonStr);

        HashMap<String, String> provinceReverseMap = new HashMap<>();

        while (matcher.find()) {
            String objStr = matcher.group(1);
            String code = extractValue(objStr, "code");
            String name = extractValue(objStr, "name");

            if (code != null && name != null) {
                provinceReverseMap.put(name, code);
            }
        }

        return provinceReverseMap;
    }
    private static String extractValue(String objStr, String key) {
        Pattern pattern = Pattern.compile("\"" + key + "\":\"([^\"]+)\"");
        Matcher matcher = pattern.matcher(objStr);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }
}
